<template>
  <div class="login">
    <div class="login-container">
      <h3 class="title" v-if="false">{{ title }}</h3>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" @keydown="handleKeydown">
        <el-form-item>
          <el-select v-model="userValue" placeholder="Select" @change="handleChangeUserValue">
            <el-option v-for="item in usersOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="用户名" size="large" :prefix-icon="User" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="密码" size="large" :prefix-icon="Lock" />
        </el-form-item>
        <el-form-item>
          <div style="display: flex; width: 100%">
            <el-button type="primary" size="large" :loading="loading" style="width: 60%" @click.native.prevent="submit(ruleFormRef)">登录</el-button>
            <el-button @click="reset(ruleFormRef)" size="large" style="flex: 1">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import Dal from '@/dal'
import { useMenusStore, useCreateView, useVisitedRoutes, useCurrentUsersStore } from '@/stores'
import { initializeDynamicRoutes } from '@/utils'
import { ElMessage } from 'element-plus'

const menusStore = useMenusStore()
const userValue = ref()
const usersOptions = ref<any[]>([])
const router = useRouter()
const title = ref(import.meta.env.VITE_SITE_TITLE)
const ruleFormRef = ref<FormInstance>()
const loading = ref(false)
const ruleForm = ref<any>({
  username: '',
  password: '123456',
})
const rules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

onMounted(() => {
  useVisitedRoutes().clearState()
  useCreateView().clearState()
  useMenusStore().clearState()
  useCurrentUsersStore().clearState()
  Dal.Users.list().then((res) => {
    usersOptions.value = res.data.map((item: any) => {
      return {
        value: item.username,
        label: item.username,
      }
    })
  })
})
const handleChangeUserValue = (value: any) => {
  if (value) {
    ruleForm.value.username = value
  }
}
/**
 * 键盘按下事件处理函数
 * @param event - 键盘事件对象
 */
const handleKeydown = (event: KeyboardEvent) => {
  // 如果按键是回车键
  if (event.key === 'Enter') {
    // 提交表单
    submit(ruleFormRef.value)
  }
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const { data } = await Dal.Users.login(ruleForm.value)
      if (data.success && data.data) {
        const { menus, user } = data.data
        menusStore.saveMenus(menus)
        useCurrentUsersStore().saveState(user)
        await initializeDynamicRoutes()
        router.push({ name: 'Home' })
      } else {
        ElMessage.error('用户名或密码错误！')
        ruleForm.value.username = ''
        ruleForm.value.password = '123456'
        loading.value = false
      }
    } else {
      loading.value = false
    }
  })
}

const reset = (formEl: FormInstance | undefined) => {
  loading.value = false
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style lang="scss" scoped>
.login {
  margin: 0 auto;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('../assets/imgs/login-background.jpg');
  background-size: cover;
  .login-container {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 30px 5px 25px;

    .title {
      margin: 0px auto 30px auto;
      text-align: center;
      color: #707070;
    }
    .el-input {
      height: 38px;
      input {
        height: 38px;
      }
    }
    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 2px;
    }
    .login-code {
      height: 38px;
      float: right;
      img {
        cursor: pointer;
        vertical-align: middle;
      }
    }
    .login-code-img {
      height: 38px;
      width: 126px;
    }
  }
}
</style>
